package com.dayou.common.utils;

import org.springframework.stereotype.Component;

import java.security.MessageDigest;

@Component
public class SHAUtil {
	public static final String KEY_SHA = "SHA";
	
	/***
	 * SHA加密（比MD5更安全）
	 * @param data
	 * @return
	 * @throws Exception
	 */
	public byte[] encryptSHA(byte[] data) throws Exception{
		MessageDigest sha = MessageDigest.getInstance(KEY_SHA);
		sha.update(data);
		return sha.digest();
	}
	
	
	public static String SHAEncrypt(String content,int offset) {
        try {
            int length = content.length();
            int splitTime = length % offset == 0 ? length / offset : length / offset + 1;
            String[] contentSplited = new String[splitTime];
            for(int i = 0;i< splitTime;i++){
                int end = (i+1)*offset;
                contentSplited[i] = content.substring(i*offset,end > length ? length : end);
            }
            StringBuffer sbf = new StringBuffer();
            for(int i = splitTime-1;i>=0;i--){
                sbf.append(contentSplited[i]);
            }
            content = sbf.toString();
            MessageDigest sha = MessageDigest.getInstance(KEY_SHA);
            byte[] sha_byte = sha.digest(content.getBytes());
            StringBuffer hexValue = new StringBuffer();
            for (byte b : sha_byte) {
                //将其中的每个字节转成十六进制字符串：byte类型的数据最高位是符号位，通过和0xff进行与操作，转换为int类型的正整数。
                String toHexString = Integer.toHexString(b & 0xff);
                hexValue.append(toHexString.length() == 1 ? "0" + toHexString : toHexString);
            }
            return hexValue.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
       return "";
    }

    public static void main(String[] args) {
	    String content = "admin123";
        int offset = (int)(Math.random()*(content.length()/2))+1;
        System.out.println(SHAEncrypt(content,offset));
    }
	
}